package com.smec.moblie.control;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import com.bigkoo.svprogresshud.SVProgressHUD;
import com.google.gson.Gson;
import com.smec.moblie.bean.AttachmentBean;
import com.smec.moblie.bean.CustomersBean;
import com.smec.moblie.bean.DeviceInfoBean;
import com.smec.moblie.bean.DeviceInfoList;
import com.smec.moblie.bean.FeedBackListBean;
import com.smec.moblie.bean.FeedbackBean;
import com.smec.moblie.bean.FeedbackContentBean;
import com.smec.moblie.bean.LoginBackBean;
import com.smec.moblie.bean.MaintenanceBean;
import com.smec.moblie.bean.MaintenanceDetailBean;
import com.smec.moblie.bean.MaintenanceDetailList;
import com.smec.moblie.bean.MaintenanceFastrepairhisBean;
import com.smec.moblie.bean.MaintenanceFastrepairhisList;
import com.smec.moblie.bean.MaintenanceList;
import com.smec.moblie.bean.MaintenanceMemoBean;
import com.smec.moblie.bean.MaintenanceMemoBeanList;
import com.smec.moblie.bean.MaintenanceNoticeBean;
import com.smec.moblie.bean.MaintenanceNoticeBeanList;
import com.smec.moblie.bean.MaintenancePhotoBean;
import com.smec.moblie.bean.MaintenancePhotoBeanList;
import com.smec.moblie.bean.MaintenancePhotoJobitemBean;
import com.smec.moblie.bean.MaintenancePhotoJobitemList;
import com.smec.moblie.bean.Mntjobitem;
import com.smec.moblie.bean.MntjobitemList;
import com.smec.moblie.bean.Mntjobtemplate;
import com.smec.moblie.bean.MntjobtemplateList;
import com.smec.moblie.bean.Mntjobtpldetail;
import com.smec.moblie.bean.MntjobtpldetailList;
import com.smec.moblie.bean.SelectListBean;
import com.smec.moblie.bean.TechHeadBean;
import com.smec.moblie.bean.TechnicalNoticeBean;
import com.smec.moblie.bean.TechnicalNoticeListBackBean;
import com.smec.moblie.bean.TechnicalNoticeUpdateBean;
import com.smec.moblie.bean.UpdatePhotoBean;
import com.smec.moblie.bean.UpdatePhotoJobitemBean;
import com.smec.moblie.common.ConstValue;
import com.smec.moblie.util.Util;
import com.smec.moblie.util.WebServiceUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;
import org.xmlpull.v1.XmlPullParserException;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.client.methods.HttpGet;
import cz.msebera.android.httpclient.client.methods.HttpPost;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;
import de.greenrobot.event.EventBus;
import okhttp3.Call;
import okhttp3.Request;

public class MainControl implements ConstValue {

    public static String getVersionCheck(Context context, String fun) {
        SharedPreferences preferences = context.getSharedPreferences("SmecMntMapService", Context.MODE_PRIVATE);
        String lo = preferences.getString("lon", "");
        String la = preferences.getString("lat", "");
        Gson gson = new Gson();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("appVer", PublicControl.getAppVersionName(context));//app版本
        hashMap.put("device", PublicControl.getDeviceId(context));//设备号
        hashMap.put("series", android.os.Build.MODEL);//设备型号
        hashMap.put("lon", lo);//经度
        hashMap.put("lat", la);//纬度
        hashMap.put("app", "Remes");//app名称
        hashMap.put("fun", fun);//接口功能
        return gson.toJson(hashMap);
    }

    /**
     * 获取版本号
     *
     * @return
     */
    public static String getVersion() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        Gson gson = new Gson();
        String jsonData = gson.toJson(map);
        String ret = callWebservice("GET_NEW_MAINTANCE_VERSION", jsonData);
        return ret;
    }

    /***
     * 登入检验
     * @param userId
     * @param passWord
     * @return 返回结果
     * @throws IOException
     * @throws XmlPullParserException
     */
    public static String checkLogon(String userId, String passWord) throws IOException, XmlPullParserException {
        // &1. 调用
        String[] keys = new String[]{"userName", "password"};
        String[] values = new String[]{userId, passWord};
        String ret = "";
        ret = WebServiceUtil.callWebservice(ConstValue.Wsdl_CheckUsernameAndPassword, "http://www.smec-cn.com", "LoginValidateInputParams", keys, values, "n0");
        if (ret.indexOf("用户名或密码错误") != -1) {
            ret = "用户名或密码错误";
        } else {
            try {
                String[] s = ret.split("displayName=");
                String[] s2 = s[1].split(";");
                ret = s2[0];
            } catch (Exception e) {
                ret = "解析错误";
            }

        }
        return ret;
    }

    /***
     * 保养列表
     *
     * @param username     户名
     * @param workorder_id 最后workorder_id
     * @return
     * @throws Exception
     */
    public static ArrayList<MaintenanceBean> getMaintenanceList(String username, String workorder_id) throws Exception {
        HashMap<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("username", username);
        hashMap.put("date_from", Util.getFrontBackStrDate(DATE_FROM));
        hashMap.put("date_to", Util.getFrontBackStrDate(DATE_TO));
        hashMap.put("last_workorderid", "0");
        Gson gson = new Gson();
        String jsonData = gson.toJson(hashMap);
        String ret = callWebServiceClob("GET_MAINTENANCE_LIST", jsonData);
        ArrayList<MaintenanceBean> maintenanceBean = new ArrayList<MaintenanceBean>();
        MaintenanceList maintenanceList;
        Log.i("", "~~getMaintenanceList ret = " + ret);
        maintenanceList = gson.fromJson(ret, MaintenanceList.class);

        if (null != maintenanceList) {

            maintenanceBean.addAll(maintenanceList.DetailList);
//            if (!"0".equals(workorder_id)) {
            ArrayList<MaintenanceBean> maintenanceBeanArrayList = new ArrayList<MaintenanceBean>();
            maintenanceBeanArrayList.addAll(DataSupport.where("assignee = ?", username).find(MaintenanceBean.class));
            HashMap<String, MaintenanceBean> maintenanceMap = new HashMap<String, MaintenanceBean>();
            for (MaintenanceBean maintenanceBean2 : maintenanceBeanArrayList) {
                maintenanceMap.put(maintenanceBean2.getWorkorder_id(), maintenanceBean2);
            }
            for (MaintenanceBean maintenanceBean1 : maintenanceBean) {
//                    ArrayList<MaintenanceBean> maintenanceBeanArrayList = (ArrayList<MaintenanceBean>) DataSupport.where("workorder_id = ?", maintenanceBean1.getWorkorder_id()).find(MaintenanceBean.class);

                if (null != maintenanceMap && maintenanceMap.size() > 0) {
                    MaintenanceBean maintenanceBean2 = maintenanceMap.get(maintenanceBean1.getWorkorder_id());
                    if (null != maintenanceBean2 && maintenanceBean2.getIsDirty() == 1) {
                        maintenanceBean1.setIsDirty(1);
                        maintenanceBean1.setDeparture_date(maintenanceBean2.getDeparture_date());
                        maintenanceBean1.setDeparture_latitude(maintenanceBean2.getDeparture_latitude());
                        maintenanceBean1.setDeparture_longitude(maintenanceBean2.getDeparture_longitude());
                        maintenanceBean1.setOnsite_date(maintenanceBean2.getOnsite_date());
                        maintenanceBean1.setOnsite_latitude(maintenanceBean2.getOnsite_latitude());
                        maintenanceBean1.setOnsite_longitude(maintenanceBean2.getOnsite_longitude());
                        if (!maintenanceBean1.getWo_status_code().equals("STATION_REJECT")) {
                            maintenanceBean1.setWo_status_code(maintenanceBean2.getWo_status_code());
                        }
                    }
                }

            }
            DataSupport.deleteAll(MaintenanceBean.class);
            maintenanceMap = null;
            maintenanceBeanArrayList = null;
            DataSupport.saveAll(maintenanceBean);
        }
        return maintenanceBean;
    }

    /***
     * 将Mntjobtemplate存入数据库
     *
     * @return ArrayList<Mntjobtemplate>
     */
    public static void getMntjobtemplate(Context context) {
        if (null == DataSupport.findFirst(Mntjobtemplate.class)) {
            MntjobtemplateList mntjobtemplateList;
            ArrayList<Mntjobtemplate> mntjobtemplate = new ArrayList<Mntjobtemplate>();
            Gson gson = new Gson();
            mntjobtemplateList = gson.fromJson(Util.readAssetsFile("mntjobtemplate.txt", context), MntjobtemplateList.class);
            mntjobtemplate.addAll(mntjobtemplateList.DetailList);
            DataSupport.saveAll(mntjobtemplate);
        }
    }

    /***
     * 将Mntjobtpldetail存入数据库
     *
     * @return ArrayList<Mntjobtpldetail>
     */
    public static void getMntjobtpldetail(Context context) {
        if (null == DataSupport.findFirst(Mntjobtpldetail.class)) {
            MntjobtpldetailList mntjobtpldetailList;
            ArrayList<Mntjobtpldetail> mntjobtpldetail = new ArrayList<Mntjobtpldetail>();
            Gson gson = new Gson();
            mntjobtpldetailList = gson.fromJson(Util.readAssetsFile("mntjobtpldetail.txt", context), MntjobtpldetailList.class);
            mntjobtpldetail.addAll(mntjobtpldetailList.DetailList);
            DataSupport.saveAll(mntjobtpldetail);
        }
    }

    /***
     * 将Mntjobitem存入数据库
     *
     * @return ArrayList<Mntjobitem>
     */
    public static void getMntjobitem(Context context) {
        if (null == DataSupport.findFirst(Mntjobitem.class)) {
            MntjobitemList mntjobitemList;
            ArrayList<Mntjobitem> mntjobitem = new ArrayList<Mntjobitem>();
            Gson gson = new Gson();
            mntjobitemList = gson.fromJson(Util.readAssetsFile("mntjobitem.txt", context), MntjobitemList.class);
            mntjobitem.addAll(mntjobitemList.DetailList);
            DataSupport.saveAll(mntjobitem);
        }
    }


    /**
     * @param username
     * @return 保养详情
     * @throws IOException
     * @throws XmlPullParserException
     */
    public static ArrayList<MaintenanceDetailBean> getMaintenanceDetail(String username) throws Exception {
        Gson gson = new Gson();
        HashMap<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("username", username);
//        hashMap.put("date_from", Util.getFrontBackStrDate(DATE_FROM));
//        hashMap.put("date_to", Util.getFrontBackStrDate(DATE_TO));
//        hashMap.put("last_workorderid", workorder_id);
        String jsonData = gson.toJson(hashMap);
        String ret = callWebServiceClob("GET_MAINTENANCE_ELEDETAIL", jsonData);
        ArrayList<MaintenanceDetailBean> maintenanceDetailBean = new ArrayList<MaintenanceDetailBean>();
        MaintenanceDetailList maintenanceDetailList;
        maintenanceDetailList = gson.fromJson(ret, MaintenanceDetailList.class);
        if (null != maintenanceDetailList) {
            DataSupport.deleteAll(MaintenanceDetailBean.class);
            maintenanceDetailBean.addAll(maintenanceDetailList.DetailList);
            DataSupport.saveAll(maintenanceDetailBean);
        }
        return maintenanceDetailBean;
    }

    /**
     * @param username
     * @return 照片数据
     * @throws IOException
     * @throws XmlPullParserException
     */
    public static ArrayList<MaintenancePhotoBean> getAllPhotoData(String username) throws Exception {
        Gson gson = new Gson();
        HashMap<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("username", username);
        hashMap.put("date_from", Util.getFrontBackStrDate(DATE_FROM));
        hashMap.put("date_to", Util.getFrontBackStrDate(DATE_TO));
        String jsonData = gson.toJson(hashMap);
        String ret = callWebServiceClob("GET_MAINTENANCE_PHOTOS", jsonData);
        ArrayList<MaintenancePhotoBean> maintenancePhotoBeans = new ArrayList<MaintenancePhotoBean>();
        MaintenancePhotoBeanList maintenancePhotoBeanList = gson.fromJson(ret, MaintenancePhotoBeanList.class);
        if (null != maintenancePhotoBeanList) {
            maintenancePhotoBeans.addAll(maintenancePhotoBeanList.DetailList);
            ArrayList<MaintenancePhotoBean> maintenancePhotoBeanArrayList = new ArrayList<MaintenancePhotoBean>();
            maintenancePhotoBeanArrayList.addAll(DataSupport.where("assignee = ?", username).find(MaintenancePhotoBean.class));
            if (maintenancePhotoBeanArrayList.size() == 0) {
                DataSupport.saveAll(maintenancePhotoBeans);
            }

        }
        return maintenancePhotoBeans;
    }

    /**
     * @param username
     * @return 急修历史
     * @throws IOException
     * @throws XmlPullParserException
     */
    public static ArrayList<MaintenanceFastrepairhisBean> getFastRepairHis(String username) throws Exception {
        Gson gson = new Gson();
        HashMap<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("username", username);
        String jsonData = gson.toJson(hashMap);
        String ret = callWebServiceClob("GET_MAINTENANCE_FASTREPAIRHIS", jsonData);
        ArrayList<MaintenanceFastrepairhisBean> maintenanceFastrepairhisBeans = new ArrayList<MaintenanceFastrepairhisBean>();
        MaintenanceFastrepairhisList maintenanceFastrepairhisList = gson.fromJson(ret, MaintenanceFastrepairhisList.class);
        if (null != maintenanceFastrepairhisList) {
            DataSupport.deleteAll(MaintenanceFastrepairhisBean.class);
            maintenanceFastrepairhisBeans.addAll(maintenanceFastrepairhisList.DetailList);
            DataSupport.saveAll(maintenanceFastrepairhisBeans);
        }
        return maintenanceFastrepairhisBeans;
    }

    /**
     * @param username
     * @return 电梯备忘
     * @throws IOException
     * @throws XmlPullParserException
     */
    public static ArrayList<MaintenanceMemoBean> getMemos(String username) throws Exception {
        Gson gson = new Gson();
        HashMap<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("username", username);
        String jsonData = gson.toJson(hashMap);
        String ret = callWebServiceClob("GET_MAINTENANCE_MEMO", jsonData);
        ArrayList<MaintenanceMemoBean> maintenanceMemoBeans = new ArrayList<MaintenanceMemoBean>();
        MaintenanceMemoBeanList maintenanceMemoBeanList = gson.fromJson(ret, MaintenanceMemoBeanList.class);
        if (null != maintenanceMemoBeanList) {
            DataSupport.deleteAll(MaintenanceMemoBean.class);
            maintenanceMemoBeans.addAll(maintenanceMemoBeanList.DetailList);
            DataSupport.saveAll(maintenanceMemoBeans);
        }
        return maintenanceMemoBeans;
    }

    /**
     * 根据用户名获取广播通知
     *
     * @param userid
     * @return
     */
    public static ArrayList<MaintenanceNoticeBean> getMaintenanceNoticeByUserId(String userid) throws IOException, XmlPullParserException {
        ArrayList<MaintenanceNoticeBean> maintenanceNoticeBeanList = new ArrayList<MaintenanceNoticeBean>();

        Gson gson = new Gson();
        HashMap<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("username", userid);
        String jsonData = gson.toJson(hashMap);

        String ret = callWebServiceClob("GET_MAINTENANCE_NOTICE", jsonData);

        MaintenanceNoticeBeanList maintenanceNoticeBeanListTemp = gson.fromJson(ret, MaintenanceNoticeBeanList.class);

        if (null != maintenanceNoticeBeanListTemp) {
            maintenanceNoticeBeanList.addAll(maintenanceNoticeBeanListTemp.DetailList);
        }

        return maintenanceNoticeBeanList;
    }

    /**
     * 获取处理日志
     *
     * @return
     */
    public static String getProblemHistory(String workorder_id) throws IOException, XmlPullParserException {

        Gson gson = new Gson();
        HashMap<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("workorder_id", workorder_id);
        String jsonData = gson.toJson(hashMap);

        String ret = callWebService("GET_HISTORY_NUM", jsonData);
        if (ret.equals("result{}")) {
            ret = "暂无遗留问题";
        }

        return ret;
    }


    /***
     * 流程接口
     * @param username
     * @param processid
     * @return 流程ID
     */
    public static int callBPMtoNextProcess(String username, String processid) {
        int resultCode = 0;
        int statusCode = 0;
        try {
            // String restURIPre =
            // "http://bpmdev.smec-cn.com:8001/SmecMobileWebService/rest/sbpmTaskQuery/v1/";
            Log.i("callBPMtoNextProcess", "~~ callBPM instanceId=" + processid);
            String restURIPre = SERVER_BASE_PATH
                    + "rest/sbpmTaskQuery/v1/";
            StringBuffer restURIBuf = new StringBuffer();
            // 获取taskID
            HttpClient httpClient = new DefaultHttpClient();
            restURIBuf.append(restURIPre);
            restURIBuf.append("insId/");
            restURIBuf.append(username);
            restURIBuf.append("?");
            restURIBuf.append("instanceId=");
            restURIBuf.append(processid);
            HttpGet httpGet = new HttpGet(restURIBuf.toString());
            HttpResponse response = httpClient.execute(httpGet);
            Log.i("343", "~~~username=" + username + "instanceId=" + processid);
            statusCode = response.getStatusLine().getStatusCode();
            Log.i("callBPMtoNextProcess", "~~ callBPM getTaskID:statusCode="
                    + statusCode);
            String taskId = null;
            if (statusCode >= 200 && statusCode < 300) {
                StringBuilder strBuilder = new StringBuilder();
                BufferedReader bufReader = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent()));
                for (String s = bufReader.readLine(); s != null; s = bufReader
                        .readLine()) {
                    strBuilder.append(s);
                }
                JSONArray jsonArray = new JSONArray(strBuilder.toString());
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = (JSONObject) jsonArray.opt(i);
                    taskId = jsonObject.getString("taskId");
                }
            } else {
                resultCode = ERR_BPM_WS;
            }
            Log.i("callBPMtoNextProcess", "~~ callBPM getTaskID:taskId="
                    + taskId);
            // 若statuscode=200， taskId为Null，视为此工单已流转过，直接返回成功
            if (200 == statusCode && taskId == null) {
                return INFO_SUCCEED;
            }
            // post taskID触发工作流
            if (taskId != null) {
                restURIBuf = new StringBuffer();
                restURIBuf.append(restURIPre);
                restURIBuf.append(username);
                restURIBuf.append("?");
                restURIBuf.append("taskId=");
                restURIBuf.append(taskId);
                restURIBuf.append("&");
                restURIBuf.append("taskResult=APPROVE");
                restURIBuf.append("&");
                restURIBuf.append("operation=");
                restURIBuf.append("保养提交");
                restURIBuf.append("&taskType=RemesMaintainance");
                HttpPost httpPost = new HttpPost(restURIBuf.toString());
                response = httpClient.execute(httpPost);
                statusCode = response.getStatusLine().getStatusCode();
                Log.i("callBPMtoNextProcess", "postTaskId=" + statusCode);
                if (statusCode >= 200 && statusCode < 300) {
                    resultCode = INFO_SUCCEED;
                } else {
                    resultCode = ERR_BPM_WS;
                }
            } else {
                resultCode = ERR_BPM_WS;
            }
        } catch (Exception e) {
            resultCode = ERR_BPM_WS;
            e.printStackTrace();
            Log.e("err", e.toString());
        }

        return resultCode;
    }

    /**
     * 上传图片数据
     *
     * @param maintenancePhotoBeanList
     * @param maintenancePhotoJobitemBeanArrayList
     * @param username
     * @return
     */
    public static Boolean updateTakePhotos(List<MaintenancePhotoBean> maintenancePhotoBeanList,
                                           ArrayList<MaintenancePhotoJobitemBean> maintenancePhotoJobitemBeanArrayList, String username) {
        Boolean ret = false;
        String jsonString = "";
        if (maintenancePhotoBeanList.size() > 0) {

            UpdatePhotoBean updatePhotoBean = new UpdatePhotoBean();
            List<UpdatePhotoBean.PhotoBean> photoBeanList = new ArrayList<>();
            for (int i = 0; i < maintenancePhotoBeanList.size(); i++) {
                MaintenancePhotoBean maintenancePhotoBean = maintenancePhotoBeanList.get(i);
                UpdatePhotoBean.PhotoBean detailListEntity = new UpdatePhotoBean.PhotoBean();
                detailListEntity.setResource_id(maintenancePhotoBean.getResource_id());
                detailListEntity.setRecord_time(maintenancePhotoBean.getRecord_time());
                detailListEntity.setWorkorder_id(maintenancePhotoBean.getWorkorder_id());
                detailListEntity.setObject_status_code(maintenancePhotoBean.getObject_status_code());
                detailListEntity.setUser_id(username);
                detailListEntity.setResource_list_id(maintenancePhotoBean.getResource_list_id());
                detailListEntity.setItem_type_code(maintenancePhotoBean.getItem_type_code());
                photoBeanList.add(detailListEntity);
            }
            updatePhotoBean.setDetailList(photoBeanList);
            Gson gson = new Gson();
            jsonString = gson.toJson(updatePhotoBean);

            String result = updateTakePhotosDataCallWebservice(
                    "CREATE_REMES_RESOURCE_LIST", jsonString);
            Log.i("updateTakePhotos", "updateTakePhotos result = " + result);
            if (null != result && !"".equals(result)) {
                try {
                    if (result.indexOf("success") != -1) {
                        ret = true;
                    } else {
                        ret = false;
                    }
                } catch (Exception e) {
                    Log.i("updateTakePhotos", "~~解析上传图片结果错误：" + e.getMessage());
                    ret = false;
                }
            }
            if (ret) {
                if (maintenancePhotoJobitemBeanArrayList.size() > 0) {
                    UpdatePhotoJobitemBean updatePhotoJobitemBean = new UpdatePhotoJobitemBean();
                    List<UpdatePhotoJobitemBean.DetailListEntity> detailListEntityList = new ArrayList<>();

                    for (int i = 0; i < maintenancePhotoJobitemBeanArrayList.size(); i++) {
                        MaintenancePhotoJobitemBean maintenancePhotoJobitemBean = maintenancePhotoJobitemBeanArrayList.get(i);
                        UpdatePhotoJobitemBean.DetailListEntity detailListEntity = new UpdatePhotoJobitemBean.DetailListEntity();
                        detailListEntity.setJob_sch_list_id(maintenancePhotoJobitemBean.getJob_sch_list_id());
                        detailListEntity.setAction_type_result(maintenancePhotoJobitemBean.getAction_type_result());
                        detailListEntity.setUsername(username);
                        detailListEntityList.add(detailListEntity);
                    }
                    updatePhotoJobitemBean.setDetailList(detailListEntityList);
                    jsonString = gson.toJson(updatePhotoJobitemBean);

                    String resultJob = updateTakePhotosDataCallWebservice(
                            "CREATE_REMES_PHOTOS", jsonString);
                    Log.i("CREATE_REMES_PHOTOS",
                            "CREATE_REMES_PHOTOS result = " + resultJob);
                    if (null != resultJob && !"".equals(resultJob)) {
                        try {
                            if (resultJob.indexOf("success") != -1) {
                                ret = true;
                            } else {
                                ret = false;
                            }
                        } catch (Exception e) {
                            Log.i("updateTakePhotos",
                                    "~~作业项上传图片结果错误：" + e.getMessage());
                            ret = false;
                        }
                    }
                }

            }

        } else {

            if (maintenancePhotoJobitemBeanArrayList.size() > 0) {
                UpdatePhotoJobitemBean updatePhotoJobitemBean = new UpdatePhotoJobitemBean();
                List<UpdatePhotoJobitemBean.DetailListEntity> detailListEntityList = new ArrayList<>();
                for (int i = 0; i < maintenancePhotoJobitemBeanArrayList.size(); i++) {
                    MaintenancePhotoJobitemBean maintenancePhotoJobitemBean = maintenancePhotoJobitemBeanArrayList.get(i);
                    UpdatePhotoJobitemBean.DetailListEntity detailListEntity = new UpdatePhotoJobitemBean.DetailListEntity();
                    detailListEntity.setJob_sch_list_id(maintenancePhotoJobitemBean.getJob_sch_list_id());
                    detailListEntity.setAction_type_result(maintenancePhotoJobitemBean.getAction_type_result());
                    detailListEntity.setUsername(username);
                    detailListEntityList.add(detailListEntity);
                }

                updatePhotoJobitemBean.setDetailList(detailListEntityList);
                Gson gson = new Gson();
                jsonString = gson.toJson(updatePhotoJobitemBean);

                String resultJob = updateTakePhotosDataCallWebservice(
                        "CREATE_REMES_PHOTOS", jsonString);
                Log.i("CREATE_REMES_PHOTOS",
                        "CREATE_REMES_PHOTOS result = " + resultJob);
                if (null != resultJob && !"".equals(resultJob)) {
                    try {
                        if (resultJob.indexOf("success") != -1) {
                            ret = true;
                        } else {
                            ret = false;
                        }
                    } catch (Exception e) {
                        Log.i("updateTakePhotos",
                                "~~作业项上传图片结果错误：" + e.getMessage());
                        ret = false;
                    }
                }
            } else {
                ret = true;
            }


        }
        return ret;
    }


    /**
     * 上传基础数据
     *
     * @param maintenanceBean
     * @return
     */
    public static int updateStatus(MaintenanceBean maintenanceBean, Context context) {
        int stepResult;
        TelephonyManager TelephonyMgr = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
        @SuppressLint("MissingPermission") String deviceId = TelephonyMgr.getDeviceId();//设备id
        try {// 修改单子状态
            Map<String, Object> submitHashMap = new LinkedHashMap<String, Object>();
            submitHashMap.put("WORKORDER_ID",
                    maintenanceBean.getWorkorder_id());
            submitHashMap.put("DEPARTURE_DATE", Util.changeToheng(maintenanceBean
                    .getDeparture_date()));
            submitHashMap.put("DEPARTURE_LONGITUDE",
                    maintenanceBean.getDeparture_longitude());
            submitHashMap.put("DEPARTURE_LATITUDE",
                    maintenanceBean.getDeparture_latitude());
            submitHashMap.put("ONSITE_DATE", Util.changeToheng(maintenanceBean
                    .getOnsite_date()));
            submitHashMap.put("ONSITE_LONGITUDE",
                    maintenanceBean.getOnsite_longitude());
            submitHashMap.put("ONSITE_LATITUDE",
                    maintenanceBean.getOnsite_latitude());
            submitHashMap.put("LEAVE_DATE", Util.changeToheng(maintenanceBean
                    .getLeave_date()));
            submitHashMap.put("LEAVE_LONGITUDE",
                    maintenanceBean.getLeave_longitude());
            submitHashMap.put("LEAVE_LATITUDE",
                    maintenanceBean.getLeave_latitude());
            submitHashMap.put("WORKORDER_DESCRIPTION",
                    maintenanceBean.getWorkorder_description());
            submitHashMap.put("FINISHED_DATE", Util.changeToheng(maintenanceBean
                    .getFinish_date()));
            String arrive_status = "";
            if (null == maintenanceBean.getArrive_status() || "".equals(maintenanceBean.getArrive_status())) {
                arrive_status = NOT_ARRIVED;
            } else {
                arrive_status = maintenanceBean.getArrive_status();
            }
//            submitHashMap.put("WO_STATUS_CODE",
//                    maintenanceBean.getWo_status_code() + "," + arrive_status);
            submitHashMap.put("WO_STATUS_CODE",
                    maintenanceBean.getWo_status_code() + "," + arrive_status + "," + deviceId);
            // 填充NULL为""
            Set set = submitHashMap.entrySet();
            Iterator iterator = set.iterator();
            while (iterator.hasNext()) {
                Map.Entry mapentry = (Map.Entry) iterator.next();
                if (mapentry.getValue() == null) {
                    mapentry.setValue("");
                }
            }

            // 调用接口上传maintenancelist
            Gson gson = new Gson();
            String jsonData = gson.toJson(submitHashMap);
            Log.i("jsonData", "~~update jsonData--------->" + jsonData);
            String retJsonStr = HttpRequestUtil.callRestUrlByJson(
                    SERVER_BASE_PATH,
                    "rest/mobile/uploaddata/v1/maintenace/", jsonData);
            System.out.println("~~update  retJsonStr------->" + retJsonStr);

            if ("SUCCESS".equals(retJsonStr)) {

                stepResult = INFO_SUCCEED;
                MaintenanceBean maintenanceBean1 = new MaintenanceBean();
                maintenanceBean1.setWo_status_code(maintenanceBean.getWo_status_code());
                maintenanceBean1.setWorkorder_description(maintenanceBean.getWorkorder_description());
                maintenanceBean1.setLeave_date(maintenanceBean.getLeave_date());
                maintenanceBean1.setFinish_date(maintenanceBean.getFinish_date());
                maintenanceBean1.setIsDirty(0);
                maintenanceBean1.update(maintenanceBean.getId());

            } else {
                stepResult = ERR_SUP_SYNC_IN_CTRL;
            }
        } catch (Exception e) {
            Log.e("submitOrderInfo", "~~~fail:" + e.getMessage());

            stepResult = ERR_SUP_SYNC_IN_CTRL;
        }

        return stepResult;
    }

    /**
     * 提交电梯备忘
     *
     * @param maintenanceMemoBeanList
     * @return
     */
    public static int updateMemo(ArrayList<MaintenanceMemoBean> maintenanceMemoBeanList) {
        int stepResult = 0;
        MaintenanceMemoBeanList memoBeanList = new MaintenanceMemoBeanList();
        memoBeanList.DetailList = maintenanceMemoBeanList;
        Gson gson = new Gson();
        String jsonString = gson.toJson(memoBeanList);

        String resultJob = updateTakePhotosDataCallWebservice(
                "CREATE_MAINTENANCE_MEMO", jsonString);
        Log.i("CREATE_MAINTENANCE_MEMO",
                "CREATE_MAINTENANCE_MEMO result = " + resultJob);
        if (null != resultJob && !"".equals(resultJob)) {
            try {
                if (resultJob.indexOf("success") != -1) {
                    stepResult = INFO_SUCCEED;
                } else {
                    stepResult = ERR_SUP_SYNC_IN_CTRL;
                }
            } catch (Exception e) {
                Log.i("CREATE_MAINTENANCE_MEMO",
                        "~~电梯备忘上传错误：" + e.getMessage());
                stepResult = ERR_SUP_SYNC_IN_CTRL;
            }
        }

        return stepResult;
    }

    /***
     * 获取保养拍照工作项
     *
     * @param username
     * @return ArrayList<MaintenancePhotoJobitemBean>
     * @throws Exception
     */
    public static ArrayList<MaintenancePhotoJobitemBean> getMaintenancePhotoJobitem(String username, String workorder_id) throws Exception {
        HashMap<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("username", username);
        hashMap.put("date_from", Util.getFrontBackStrDate(DATE_FROM));
        hashMap.put("date_to", Util.getFrontBackStrDate(DATE_TO));
        hashMap.put("last_workorderid", "0");
        Gson gson = new Gson();
        String jsonData = gson.toJson(hashMap);
        String ret = callWebServiceClob("GET_MAINTENANCE_PHOTO_JOBITEM", jsonData);
        Log.i("", "~~getMaintenancePhotoJobitem ret = " + ret);
        ArrayList<MaintenancePhotoJobitemBean> maintenancePhotoJobitemBeanList = new ArrayList<MaintenancePhotoJobitemBean>();
        MaintenancePhotoJobitemList maintenancePhotoJobitemList;
        maintenancePhotoJobitemList = gson.fromJson(ret, MaintenancePhotoJobitemList.class);
        if (null != maintenancePhotoJobitemList) {
            maintenancePhotoJobitemBeanList.addAll(maintenancePhotoJobitemList.DetailList);
//            for (MaintenancePhotoJobitemBean maintenancePhotoJobitemBean : maintenancePhotoJobitemBeanList) {
//                maintenancePhotoJobitemBean.saveIfNotExist();
//            }
            ArrayList<MaintenancePhotoJobitemBean> maintenanceBeanArrayList = new ArrayList<MaintenancePhotoJobitemBean>();
            maintenanceBeanArrayList.addAll(DataSupport.where("assignee = ?", username).find(MaintenancePhotoJobitemBean.class));
            HashMap<String, MaintenancePhotoJobitemBean> maintenanceMap = new HashMap<String, MaintenancePhotoJobitemBean>();
            for (MaintenancePhotoJobitemBean maintenancePhotoJobitemBean1 : maintenanceBeanArrayList) {
                maintenanceMap.put(maintenancePhotoJobitemBean1.getJob_sch_list_id(), maintenancePhotoJobitemBean1);
            }
            for (MaintenancePhotoJobitemBean maintenancePhotoJobitemBean1 : maintenancePhotoJobitemBeanList) {
                MaintenancePhotoJobitemBean maintenanceBeanTemp = maintenanceMap.get(maintenancePhotoJobitemBean1.getJob_sch_list_id());
                if (null != maintenanceBeanTemp) {
                    maintenancePhotoJobitemBean1.setAction_type_result(maintenanceBeanTemp.getAction_type_result());
                }
            }
            DataSupport.deleteAll(MaintenancePhotoJobitemBean.class);
            maintenanceMap = null;
            maintenanceBeanArrayList = null;
            DataSupport.saveAll(maintenancePhotoJobitemBeanList);
        }
        return maintenancePhotoJobitemBeanList;
    }

    /***
     * 获取保养电梯的急修历史
     *
     * @param username
     * @return ArrayList<MaintenanceFastrepairhisBean>
     */
    public static ArrayList<MaintenanceFastrepairhisBean> getMaintenanceFastrepairhi(String username) throws Exception {
        ArrayList<MaintenanceFastrepairhisBean> MaintenanceFastrepairhisBean = new ArrayList<MaintenanceFastrepairhisBean>();
        HashMap<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("username", username);
        Gson gson = new Gson();
        String jsonData = gson.toJson(hashMap);
        String ret = callWebServiceClob("GET_MAINTENANCE_FASTREPAIRHIS", jsonData);
        MaintenanceFastrepairhisList maintenanceFastrepairhisList;
        maintenanceFastrepairhisList = gson.fromJson(ret, MaintenanceFastrepairhisList.class);
        if (null != maintenanceFastrepairhisList) {
            MaintenanceFastrepairhisBean.addAll(maintenanceFastrepairhisList.DetailList);
            DataSupport.deleteAll(MaintenanceFastrepairhisBean.class);
            DataSupport.saveAll(MaintenanceFastrepairhisBean);
        }
        return MaintenanceFastrepairhisBean;
    }

    /***
     * 获取设备领用人信息
     *
     * @param deviceid
     * @return ArrayList<DeviceInfoBean>
     */
    public static ArrayList<DeviceInfoBean> getDeviceInfo(String deviceid) throws Exception {
        ArrayList<DeviceInfoBean> returnList = new ArrayList<DeviceInfoBean>();
        HashMap<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("imei_num", deviceid);
        Gson gson = new Gson();
        String jsonData = gson.toJson(hashMap);
        String ret = callWebServiceClob("GET_MNT_DEVICE", jsonData);
        DeviceInfoList deviceInfoList;
        deviceInfoList = gson.fromJson(ret, DeviceInfoList.class);
        if (null != deviceInfoList) {
            returnList.addAll(deviceInfoList.DetailList);
        }
        return returnList;
    }

    /**
     * 获取技术通知单列表数据
     *
     * @param type        当值为TASK，查询待办列表；当值为HISTORY，查询历史记录列表
     * @param contentText 查询包括 保养作业编号，合同号梯号，客户名称，要求完成日期（当content内容为空时，默认获取所有列表）
     */
    public static void getTechnicalNoticeList(String type, String contentText, Context context) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("type", type);
        hashMap.put("content", contentText);
        final Gson gson = new Gson();
        String jsonString = gson.toJson(hashMap);
        Log.i("", "~~getTechnicalNoticeList gson = " + jsonString);

        SharedPreferences preferences = context.getSharedPreferences("ElevatorSharedPreferences", Context.MODE_PRIVATE);

        OkHttpUtils.postString().addHeader(TOKEN, preferences.getString("TOKEN", "")).addHeader(TRACE, getVersionCheck(context, "getTechnicalNoticeList")).url(QUERY_CONTENT_LIST_SERVICE_URL).content(jsonString).build().execute(new StringCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {
                EventBus.getDefault().post(new EventCenter.TechnicalNoticeListBackFailed("连接服务器失败"));
            }

            @Override
            public void onResponse(String response, int id) {
                Log.i("", "~~getTechnicalNoticeList back = " + response);
                TechnicalNoticeListBackBean technicalNoticeListBackBean = gson.fromJson(response, TechnicalNoticeListBackBean.class);
                if (technicalNoticeListBackBean.getCode().equals("SUCCESS")) {
                    DataSupport.deleteAll(CustomersBean.class);
                    DataSupport.deleteAll(TechHeadBean.class);
                    DataSupport.deleteAll(TechnicalNoticeBean.class);
                    DataSupport.deleteAll(AttachmentBean.class);
                    DataSupport.saveAll(technicalNoticeListBackBean.getData().getCustomers());
                    DataSupport.saveAll(technicalNoticeListBackBean.getData().getTechHead());
                    DataSupport.saveAll(technicalNoticeListBackBean.getData().getTechLines());
                    for (TechHeadBean techHeadBean : technicalNoticeListBackBean.getData().getTechHead()) {
                        DataSupport.saveAll(techHeadBean.getAttachment());
                    }

                    EventBus.getDefault().post(new EventCenter.TechnicalNoticeListBackSuccess());
                } else {
                    EventBus.getDefault().post(new EventCenter.TechnicalNoticeListBackFailed(technicalNoticeListBackBean.getUserMsg()));
                }
            }
        });

    }

    /**
     * 获取保养作业详情
     *
     * @param itemId
     * @param context
     */
    public static void getFeedbackList(final int itemId, Context context) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("itemId", itemId);
        final Gson gson = new Gson();
        String jsonString = gson.toJson(hashMap);
        Log.i("", "~~getTechnicalNoticeList gson = " + jsonString);

        SharedPreferences preferences = context.getSharedPreferences("ElevatorSharedPreferences", Context.MODE_PRIVATE);
        String tokenString = preferences.getString("TOKEN", "");

        OkHttpUtils.postString().addHeader(TOKEN, tokenString).addHeader(TRACE, getVersionCheck(context, "getFeedbackList")).url(GET_ITEM_DETAILS_SERVICE_URL).content(jsonString).build().execute(new StringCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {
                EventBus.getDefault().post(new EventCenter.FeedBackListBackFailed("连接服务器失败"));
            }

            @Override
            public void onResponse(String response, int id) {
                Log.i("", "~~getTechnicalNoticeList back = " + response);
                FeedBackListBean feedBackListBean = gson.fromJson(response, FeedBackListBean.class);
                if (feedBackListBean.getCode().equals("SUCCESS")) {
                    DataSupport.deleteAll(FeedbackBean.class, "itemId = ?", itemId + "");
                    DataSupport.saveAll(feedBackListBean.getData().getFeedback());
                    for (FeedbackBean feedbackBean : feedBackListBean.getData().getFeedback()) {
                        if (feedbackBean.getFeedbackContent() != null) {
                            DataSupport.deleteAll(FeedbackContentBean.class, "feedbackId = ? AND itemId = ?", feedbackBean.getFeedbackContent().getFeedbackId() + "", itemId + "");
                            feedbackBean.getFeedbackContent().save();
                            if (feedbackBean.getFeedbackContent().getSelectList() != null) {
                                DataSupport.deleteAll(SelectListBean.class, "feedbackId = ? AND itemId = ?", feedbackBean.getFeedbackContent().getFeedbackId() + "", itemId + "");
                                DataSupport.saveAll(feedbackBean.getFeedbackContent().getSelectList());
                            }

                        }
                    }
                    EventBus.getDefault().post(new EventCenter.FeedBackListBackSuccess());
                } else {
                    EventBus.getDefault().post(new EventCenter.FeedBackListBackFailed(feedBackListBean.getUserMsg()));
                }
            }
        });

    }

    /**
     * 个性化保养-提交反馈项
     *
     * @param technicalNoticeUpdateBean
     * @param context
     */
    public static void submitFeedbackList(TechnicalNoticeUpdateBean technicalNoticeUpdateBean, Context context) {
        final Gson gson = new Gson();
        String jsonString = gson.toJson(technicalNoticeUpdateBean);
        Log.i("", "~~submitFeedbackList gson = " + jsonString);

        SharedPreferences preferences = context.getSharedPreferences("ElevatorSharedPreferences", Context.MODE_PRIVATE);
        String tokenString = preferences.getString("TOKEN", "");
        OkHttpUtils.postString().addHeader(TOKEN, tokenString).addHeader(TRACE, getVersionCheck(context, "submitFeedbackList"))
                .url(SUBMIT_FEEDBACK_SERVICE_URL)
                .content(jsonString).build()
                .connTimeOut(60000)
                .readTimeOut(60000)      // 设置当前请求的读取超时时间
                .writeTimeOut(60000)
                .execute(new StringCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {
                EventBus.getDefault().post(new EventCenter.submitFeedbackListFailed("连接服务器失败"));
            }

            @Override
            public void onResponse(String response, int id) {
                Log.i("", "~~submitFeedbackList back = " + response);
                LoginBackBean loginBackBean = gson.fromJson(response, LoginBackBean.class);
                if (loginBackBean.getCode().equals("SUCCESS")) {
                    EventBus.getDefault().post(new EventCenter.submitFeedbackListSuccess());
                } else {
                    EventBus.getDefault().post(new EventCenter.submitFeedbackListFailed(loginBackBean.getUserMsg()));
                }
            }
        });

    }

    /**
     * 下载文件
     *
     * @param url
     * @param name
     * @param context
     */
    public static void getFile(String url, String name, final Context context) {
        OkHttpUtils.get().url(url).build().execute(new FileCallBack(Environment.getExternalStorageDirectory() + PICTUREPATH, name) {
            SVProgressHUD mSVProgressHUD;
            boolean isProgress;

            @Override
            public void onError(Call call, Exception e, int id) {
                Toast.makeText(context, "下载文件失败,原因：" + e.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(File response, int id) {
                if (mSVProgressHUD.isShowing()) {
                    mSVProgressHUD.dismiss();
                }
                try {
                    context.startActivity(PublicControl.getOpenFileIntent(response));
                } catch (Exception e) {
                    Toast.makeText(context, "缺少打开文件的应用，文件打开失败，请下载相关应用后再尝试打开", Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void onBefore(Request request, int id) {
//                isProgress = true;
                isProgress = false;
                mSVProgressHUD = new SVProgressHUD(context);
//                mSVProgressHUD.showWithProgress("进度 " + 0 + "%", SVProgressHUD.SVProgressHUDMaskType.Black);
                super.onBefore(request, id);
            }

            @Override
            public void onAfter(int id) {
                super.onAfter(id);
            }

            @Override
            public void inProgress(float progress, long total, int id) {
                if (isProgress) {
                    if (total != -1) {
                        if (mSVProgressHUD.getProgressBar().getMax() != mSVProgressHUD.getProgressBar().getProgress()) {
                            mSVProgressHUD.getProgressBar().setProgress((int) (progress * 100));
                            mSVProgressHUD.setText("进度 " + progress * 100 + "%");
                        } else {
                            mSVProgressHUD.dismiss();
                        }
                    } else {
                        mSVProgressHUD.showWithStatus("文件下载中...");
                        isProgress = false;
                    }
                }
                super.inProgress(progress, total, id);
            }
        });
    }

    /**
     * 上传照片项数据
     *
     * @param type
     * @param p_parameters
     * @return
     */
    private static String updateTakePhotosDataCallWebservice(String type,
                                                             String p_parameters) {
        String ret = null;
        // &1. 调用
        String[] keys = new String[]{"p_data_type", "p_parameters"};
        String[] values = new String[]{type, p_parameters};
        try {
            ret = WebServiceUtil.callWebservice(
                    ConstValue.UPDATETAKEPHOTOS,
                    "http://www.smec-cn.com/inst", "GetDataByType", keys,
                    values, "n0");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        }
        return ret;

    }


    /**
     * 更改文件名称
     **/
    public static boolean renameToNewFile(String src, String dest) {
        File srcDir = new File(src);  //就文件夹路径
        boolean isOk = srcDir.renameTo(new File(dest));  //dest新文件夹路径，通过renameto修改
        System.out.println("renameToNewFile is OK ? :" + isOk);
        return isOk;
    }

    public static String callWebServiceClob(String data_type, String jsonData) throws IOException, XmlPullParserException {
        String ret = "";
        String[] keys = new String[]{"p_data_type", "p_parameters"};
        String[] values = new String[]{data_type, jsonData};
        ret = WebServiceUtil.callWebservice(ConstValue.clobdata, "http://www.smec-cn.com/inst", "GetClobDataByType", keys, values, "n0");
        return ret;
    }

    private static String callWebService(String data_type, String jsonData) throws IOException, XmlPullParserException {
        String ret = "";
        String[] keys = new String[]{"p_data_type", "p_parameters"};
        String[] values = new String[]{data_type, jsonData};
        ret = WebServiceUtil.callWebservice(ConstValue.data, "http://www.smec-cn.com/remesmobile", "GetDataByType", keys, values, "n0");
        return ret;
    }

    // call webservice
    private static String callWebservice(String type, String p_parameters) {
        String ret = null;
        // &1. 调用
        String[] keys = new String[]{"p_data_type", "p_parameters"};
        String[] values = new String[]{type, p_parameters};
        for (int i = 0; i < 3; i++) {
            if (null == ret || "".equals(ret)) {

                try {
                    ret = WebServiceUtil.callWebservice(data,
                            "http://www.smec-cn.com/remesmobile", "GetDataByType",
                            keys, values, "n0");
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (XmlPullParserException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return ret;

    }
}
